package com.ruoyi.common.core.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IDCardValidator {
    // 校验身份证号码的方法
    public static boolean isValidIDCard(String idCard) {
        // 身份证号码长度必须是18位
        if (idCard == null || idCard.length() != 18) {
            return false;
        }

        // 正则表达式验证格式
        String regex = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(idCard);
        if (!matcher.matches()) {
            return false;
        }

        // 验证校验码
        return  true;
//        return validateChecksum(idCard);
    }

    // 验证校验码的方法
    private static boolean validateChecksum(String idCard) {
        // 系数数组
        int[] factors = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        // 校验码数组
        char[] checksumChars = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

        // 计算校验码
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += Character.getNumericValue(idCard.charAt(i)) * factors[i];
        }
        int checksumIndex = sum % 11;
        char expectedChecksum = checksumChars[checksumIndex];

        // 比较计算出的校验码和身份证号码中的校验码
        char actualChecksum = Character.toUpperCase(idCard.charAt(17));
        return expectedChecksum == actualChecksum;
    }
    public static String getGenderFromIdCard(String idCardNumber) {
        if (idCardNumber == null || idCardNumber.length() != 18) {
            throw new IllegalArgumentException("身份证号码格式不正确");
        }

        // 获取身份证号码的第17位字符
        char genderChar = idCardNumber.charAt(16);

        // 将字符转换为数字
        int genderNum = Character.getNumericValue(genderChar);

        // 判断性别
        if (genderNum % 2 == 0) {
            return "女";
        } else {
            return "男";
        }
    }

    public static void main(String[] args) {
        String idCardNumber = "11010519491231002X";
        String gender = getGenderFromIdCard(idCardNumber);
        System.out.println("性别: " + gender); // 输出: 性别: 女

        // 测试示例
        String idCard1 = "440883198402184258";
        String idCard2 = "22";

        System.out.println("身份证号码 " + idCard1 + " 的校验结果: " + isValidIDCard(idCard1));
        System.out.println("身份证号码 " + idCard2 + " 的校验结果: " + isValidIDCard(idCard2));
    }
}
